/*
 * MapStaticContext.java
 *
 * Created on April 15, 2005, 3:07 PM
 */

package com.smallx.xpath;

import java.io.IOException;
import java.util.*;
import java.net.*;
import java.util.logging.Logger;
import org.infoset.xml.Document;
import org.infoset.xml.DocumentLoader;
import org.infoset.xml.Element;
import org.infoset.xml.Name;
import org.infoset.xml.NamespaceScope;
import org.infoset.xml.XMLException;
import org.infoset.xml.sax.SAXDocumentLoader;

/**
 *
 * @author R. Alexander Milowski
 */
public class SimpleStaticContext implements StaticContext
{
   public static final Map<String,URI> emptyPrefixes = Collections.emptyMap();
   public static final Set<Name> emptyVariables = Collections.emptySet();

   URI baseURI;
   Map<URI,Document> documentCache;
   Map<String,URI> prefixes;
   Set<Name> variables;
   NamespaceScope scope;
   DocumentLoader docLoader;
   Logger log;
   
   
   public SimpleStaticContext() {
      this(null,emptyPrefixes,emptyVariables);
   }
   /** Creates a new instance of MapStaticContext */
   public SimpleStaticContext(URI baseURI, Map<String,URI> prefixes, Set<Name> variables)
   {
      this.baseURI = baseURI;
      this.prefixes = prefixes;
      this.scope = new NamespaceScope(NamespaceScope.getDefaultScope(),prefixes);
      this.variables = Collections.unmodifiableSet(variables);
      this.docLoader = new SAXDocumentLoader();
      this.log = Logger.getLogger(SimpleStaticContext.class.getName());
      this.documentCache = new HashMap<URI,Document>();
   }
   
   public SimpleStaticContext(Element context, Set<Name> variables)
   {
      this(context.getBaseURI(),context.getNamespaceScope().getDataProxy(),variables);
   }
   
   public void setTraceLog(Logger log) {
      this.log = log;
   }
   
   public Logger getTraceLog() {
      return log;
   }
   
   public DocumentLoader getDocumentLoader() {
      return docLoader;
   }

   public URI getBaseURI()
   {
      return baseURI;
   }

   public Set<Name> getInScopeVariables()
   {
      return variables;
   }

   public NamespaceScope getNamespaceScope()
   {
      return scope;
   }
   
   public Set<Document> getCollection(URI collection) {
      return null;
   }
   
   public Document getDocument(URI location) 
      throws XMLException
   {
      Document doc = documentCache.get(location);
      if (doc!=null) {
         return doc;
      }
      try {
         doc = docLoader.load(location);
         documentCache.put(location,doc);
         return doc;
      } catch (IOException ex) {
         throw new XMLException("Cannot load "+location+" due to I/O error.",ex);
      }
   }
   
}
